package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;

public class GuanchaNewsAnalyse implements AnalyseNews {

	//http://www.guancha.cn/society/2013_05_07_142877.shtml
	private static final String[] regex={
		"http://www.guancha.cn/.*/[0-9]*_[0-9]*_[0-9]*_[0-9]*_s.shtml",
		"http://www.guancha.cn/.*/[0-9]*_[0-9]*_[0-9]*_[0-9]*.shtml",
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		NewsMeta news=new NewsMeta();

		String htmltxt=urlMeta.getHtml();
		Document doc=Jsoup.parse(htmltxt);
		String title=null;
		String content=null;
		Long date=null;
		String author=null;

		doc.select("div.readers").remove();
		doc.select("div.observation").remove();
		doc.select("div.right-side01").remove();

		title=doc.select("h2.content-title1").text();
		if (StringUtils.isBlank(title)) {
			title=doc.select("a.title_1st").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div.all-txt p"));
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("p.top-padding3"));
		}
		date=DateUtils.matchDate(doc.select("span.time").text());
		if(date == null)
		date=DateUtils.matchDate(doc.select("div.txt-info").text());

		author=JSoupUtils.matchAuthor(doc, "来源:");
		news.setAuthor(author);
		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		String url="http://www.guancha.cn/YiGeEr%C2%B7YiWanNuoFu/2014_07_12_245457.shtml";
		GuanchaNewsAnalyse test=new GuanchaNewsAnalyse();
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(test.isDetailPage(url));
		System.out.println(DoMainUtils.GetDomainName(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
